package com.stiff.search.controller;

import com.stiff.search.pojo.SearchResult;
import com.stiff.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class SearchController {
    @Autowired
    private SearchService searchService;
    @RequestMapping(value = "search",method = RequestMethod.GET)
    public ModelAndView search(@RequestParam("q")String keyWords,@RequestParam(value = "page",defaultValue = "1")Integer page){
        ModelAndView mv =new ModelAndView("search");
        try {
            //解决中文乱码
            keyWords = new String(keyWords.getBytes("ISO-8859-1"),"UTF-8");
            SearchResult searchResult = this.searchService.search(keyWords,page);
            mv.addObject("query",keyWords);
            mv.addObject("itemList",searchResult.getData());
            mv.addObject("page",page);
            int total = searchResult.getTotal().intValue();
            int pages = total % searchService.ROWS == 0 ? total /searchService.ROWS : total /searchService.ROWS + 1;
            mv.addObject("pages",pages);
            return mv;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}